package com.example.demo.controller;

import com.example.demo.domain.*;
import com.example.demo.repository.ExpressMapper;
import com.example.demo.repository.OrderMapper;
import com.example.demo.service.ExpressService;
import com.example.demo.service.GoodsService;
import com.example.demo.service.OrderService;
import com.example.demo.utils.TimeUtils;
import org.apache.catalina.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Create:     Space
 * @Time:       2020-6-18 20:18:00
 * @Describe:
 */
@Controller
public class OrderController
{
    @Value("${ip}")
    private String ip;
    @Value("${server.port}")
    private String port;
    @Value("${uploadGoodsPath}")
    private String uploadGoodsPath;
    @Value("${uploadIconPath}")
    private String uploadIconPath;
    @Value("${goodsPicPathPattern}")
    private String goodsPicPathPattern;
    @Value("${iconPathPattern}")
    private String iconPathPattern;
    @Resource
    private OrderService orderService;
    @Resource
    private ExpressService expressService;
    @Resource
    private GoodsService goodsService;


    @RequestMapping("/orders")
    public String list(Model model, @RequestParam(value = "searchText",required = false) String searchText)
    {
        System.out.println(searchText);
        if(searchText==null)
        {
            model.addAttribute("orders", orderService.getOrder(1));
            return "admin/orders";
        }
        else if(searchText.length()>0)
        {
            model.addAttribute("orders", orderService.getSearch(searchText,1 ));
            return "admin/orders";
        }
        else
        {
            return "redirect:/orders";
        }
    }

    @GetMapping("/order/{id}")
    public String toEdit(@PathVariable("id") Integer id, Model model)
    {
        System.out.println("get:"+"/order/"+id);
        model.addAttribute("order",orderService.getOrderById(id));
        return "admin/confirmOrder";
    }


    @PostMapping("/order/{id}")
    public String updateOrder(@PathVariable("id") Integer id, Model model,String expressNo,String expressCom)
    {
        System.out.println("post:"+"/order/"+id);
        System.out.println(expressNo+" "+expressCom);
        Express express=new Express();
        express.setNu(expressNo);
        express.setCom(expressCom);
        express.setTimes(TimeUtils.getStringDate());
        expressService.addExpress(express);
        Order order=orderService.getOrderById(id);
        order.setEid(expressService.getIdByNu(expressNo));
        order.setState(2);
        orderService.saveOrder(order);
        return "redirect:/orders";
    }


    @RequestMapping("/returns")
    public String listReturn(Model model, @RequestParam(value = "searchText",required = false) String searchText)
    {
        System.out.println(searchText);
        if(searchText==null)
        {
            model.addAttribute("orders", orderService.getOrder(4));
            return "admin/returns";
        }
        else if(searchText.length()>0)
        {
            model.addAttribute("orders", orderService.getSearch(searchText,4 ));
            return "admin/returns";
        }
        else
        {
            return "redirect:/returns";
        }
    }


    @PostMapping("/return/{id}")
    public String updateReturn(@PathVariable("id") Integer id, Model model)
    {
        System.out.println("post:"+"/return/"+id);

        return "redirect:/returns";
    }


    @GetMapping("/return/{id}")
    public String viewReturn(@PathVariable("id") Integer id, Model model)
    {
        System.out.println("get:"+"/return/"+id);
        model.addAttribute("order",orderService.getOrderById(id));
        return "admin/confirmReturn";
    }


    @RequestMapping("/historyOrders")
    public String listHistoryOrder(Model model, @RequestParam(value = "searchText",required = false) String searchText)
    {
        System.out.println(searchText);
        if(searchText==null)
        {
            model.addAttribute("orders", orderService.getHistoryOrders());
            return "admin/historyOrders";
        }
        else if(searchText.length()>0)
        {
            model.addAttribute("orders", orderService.getHistoryOrderSearch(searchText));
            return "admin/historyOrders";
        }
        else
        {
            return "redirect:/historyOrders";
        }
    }


    @RequestMapping("/historyOrder/{id}")
    public String viewHistoryOrder(@PathVariable("id") Integer id, Model model)
    {
        System.out.println("post:"+"/return/"+id);
        model.addAttribute("order",orderService.getOrderById(id));
        return "admin/historyOrder";
    }


    @RequestMapping("/delCart/{id}")
    public String delCart(@PathVariable("id") Integer id)
    {
        orderService.delOrderById(id);
        return "redirect:/show/order/cart";
    }

    @RequestMapping("/addCart")
    public String addCart(Model model, @RequestParam("gid") Integer gid, @RequestParam("goodsNum") Integer goodsNum, HttpServletRequest request, RedirectAttributes redirectAttributes)
    {

        User user= (User) request.getSession().getAttribute("user");
        System.out.println(gid);
        System.out.println(goodsNum);
        Goods goods=goodsService.getGoodsById(gid);

        if (user==null)
        {
            redirectAttributes.addFlashAttribute("msg","请先登录");
        }
        else
        {
            Order order=new Order();
            order.setState(0);
            order.setUid(user.getId());
            order.setUser(user);
            order.setTimes(TimeUtils.getStringDate());
            order.setGoodsNum(goodsNum);
            order.setBuying_price(goods.getBuying_price());
            order.setSelling_price(goods.getSelling_price());
            order.setGid(goods.getId());
            order.setAid(0);
            orderService.addOrder(order);
            redirectAttributes.addFlashAttribute("msg","添加成功");
        }
        return "redirect:/goodDetail/"+goods.getId();
    }

    @RequestMapping("/buy")
    public String buy(Model model, @RequestParam("gid") Integer gid, @RequestParam("goodsNum") Integer goodsNum, HttpServletRequest request, RedirectAttributes redirectAttributes)
    {

        User user= (User) request.getSession().getAttribute("user");
        System.out.println(gid);
        System.out.println(goodsNum);
        Goods goods=goodsService.getGoodsById(gid);
        if (user==null)
        {
            redirectAttributes.addFlashAttribute("msg","请先登录");
            return "redirect:/goodDetail/"+goods.getId();
        }
        else
        {
            Order order=new Order();
            order.setState(0);
            order.setUid(user.getId());
            order.setUser(user);
            order.setTimes(TimeUtils.getStringDate());
            order.setGoodsNum(goodsNum);
            order.setBuying_price(goods.getBuying_price());
            order.setSelling_price(goods.getSelling_price());
            order.setGid(goods.getId());
            order.setAid(0);
            orderService.addOrder(order);
            return "redirect:/show/address/choose/"+orderService.getIdByOrder(order);
        }
    }

    /*
     * @Author : LT4
     * @Description: 用于返回前端的 order数据
     * */
    //购物车
    //每页默认3条记录
    @GetMapping("/show/order/cart")
    public ModelAndView showCartOrder(@RequestParam(value = "pageNum",required = false,defaultValue = "1") Integer pageNum,
                                      @RequestParam(value = "pageSize",required = false,defaultValue = "3") Integer pageSize,
                                      ModelAndView modelAndView, HttpServletRequest request){
        int start=(pageNum-1)*pageSize;
        if(pageNum>1)start++;
        int end=pageNum*pageSize;
        Page page=new Page(pageNum,pageNum-1,pageNum+1);


        HttpSession session=request.getSession();
        User user= (User) session.getAttribute("user");
        List<Order> orders=null;
        if(user==null){
            orders=orderService.getCartOrderByUid(1,start,end);
        }else{
            orders=orderService.getCartOrderByUid(user.getId(),start,end);
        }
        System.out.println(orders);
        modelAndView.setViewName("/show/order/cart");
        modelAndView.addObject("orders",orders);
        modelAndView.addObject("page",page);
        modelAndView.addObject("goodsPicPath", "http://"+ip+":"+port+goodsPicPathPattern);
        return modelAndView;
    }

    //已支付订单
    //每页默认3条记录
    @GetMapping("/show/order/list")
    public ModelAndView showNoCartOrder(@RequestParam(value = "pageNum",required = false,defaultValue = "1") Integer pageNum,
                                        @RequestParam(value = "pageSize",required = false,defaultValue = "3") Integer pageSize,
                                        ModelAndView modelAndView, HttpServletRequest request){
        int start=(pageNum-1)*pageSize;
        if(pageNum>1)start++;
        int end=pageNum*pageSize;
        Page page=new Page(pageNum,pageNum-1,pageNum+1);

        HttpSession session=request.getSession();
        User user= (User) session.getAttribute("user");
        List<Order> orders=null;
        if(user==null){
            orders=orderService.getNonCartOrderByUid(1,start,end);
        }else{
            orders=orderService.getNonCartOrderByUid(user.getId(),start,end);
        }
        System.out.println(orders);
        modelAndView.setViewName("/show/order/list");
        modelAndView.addObject("orders",orders);
        modelAndView.addObject("page",page);
        modelAndView.addObject("goodsPicPath", "http://"+ip+":"+port+goodsPicPathPattern);
        return modelAndView;
    }

    //修改订单状态
    @ResponseBody
    @PutMapping("/show/order/state")
    public Map changeOrderState(@RequestBody Order order){
        System.out.println(order);
        orderService.saveOrderState(order.getId(),order.getState());
        Map<String,String> map=new HashMap<String,String>();
        map.put("msg","success");
        //0：购物车  1：支付   2：后台同意   3：收货   4：退货    5：后台同意
        if(order.getState()==1){
            map.put("locate","/show/order/cart");
        }else{
            map.put("locate","/show/order/list");
        }
        return map;
    }

    /*------------------------end---------------------------------*/


}
